import React from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Icon,Picker } from 'weaver-mobile';
import LayoutTr from '../layout/LayoutTr';
import { _, ParseUtil, DetailUtil } from '../../util/pcPublic';
import { getLabel } from '../../util/common';

@inject('wfGlobalStore','wfLayoutStore')
@withRouter
@observer
export default class DetailLayout extends React.Component {
    render() {
        const { symbol,wfGlobalStore,wfLayoutStore } = this.props;
        const groupid = parseInt(symbol.substring(7)) - 1;
        const { commonParam } = wfGlobalStore;
        const { layouttype } = commonParam;
        const { dataJson,detailMap } = wfLayoutStore;
        const detailLayout = dataJson.etables[symbol] || {};
        const headRow = parseInt(detailLayout.edtitleinrow || 0);
        const tailRow = parseInt(detailLayout.edtailinrow || 0);
        if(headRow == 0 || tailRow == 0 || tailRow <= headRow) {
            return <div>{getLabel(386148,'对不起，表头标识、表尾标识设置异常，无法渲染明细！')}</div>
        }
        if(!detailMap.has(symbol)){
            return <div>表单中不存在此明细表，请检查模板配置！</div>
        }
        const detailObj = detailMap.get(symbol);
        const detailAttr = detailObj.attr;
        const allowXScroll = detailAttr.allowscroll === 1;
        const isSeniorSet = detailLayout.seniorset === "1";
        const { rowattrs,colattrs,rowheads,colheads,ec } = detailLayout;
        let divClassName = allowXScroll ? "excelDetailContent wf-detailScroll" : "excelDetailContent";
        let tableStyle = {};
        //let tableStyle = ParseUtil.judgeDetailContainColHide(colattrs) ? {"table-layout":"fixed"} : {}; 
        const rowHeads = ParseUtil.convertRowHeads(rowheads);
        const colHeads = ParseUtil.convertColHeads(colheads, symbol, layouttype, tableStyle, allowXScroll, isSeniorSet);
        const ecMap = ParseUtil.convertEcMap(ec);
        //解析列宽
        let colTdArr = new Array();
        if(!isSeniorSet)
            colTdArr.push(<td style={{width:allowXScroll ? "60px" : "6%"}} />);
        colHeads.map((o,index)=>{
            let colStyle = {width:o.width};
            const colCusAttr = colattrs && colattrs[`col_${o.id}`] || {};
            let colClassName = "";
            if(colCusAttr.hide === "y")
                colClassName += " detail_hide_col";
            if(!!colCusAttr.class)
                colClassName += " "+colCusAttr.class;
            colTdArr.push(<td key={index} style={colStyle} className={colClassName} />);
        });
        //解析数据行
        let trHeadArr = new Array();   //头部行
        trHeadArr.push(<tr key="detailControlWidth" className="detailControlWidth">{colTdArr}</tr>);
        let trDataArr = new Array();   //数据行
        let trTailArr = new Array();   //尾部行
        ParseUtil.parseLayoutImage(detailLayout, tableStyle, trHeadArr);    //解析背景图、悬浮图,置于头部行
        const { currentPageRowArr,rowInfo,currentPageRowMergeInfo } = detailObj;
        rowHeads.map(row=>{
            const rowid = parseInt(row.id);
            const rowCusAttr = rowattrs ? rowattrs["row_"+rowid] : null;
            let addColType = 0;
            const dataRows = tailRow - headRow - 1;
            if(rowid === headRow+1) {    //明细数据行
                if(!isSeniorSet)
                    addColType = 3;
                currentPageRowArr.length>0 && currentPageRowArr.map(_info =>{
                    const { rowIndex,serialNum } = _info;
                    const rowAttr = rowInfo.get(`row_${rowIndex}`);
                    const detailProps = {addColType, rowIndex, serialNum, needHide:rowAttr.get("needHide"), isDetailShow:true};
                    for(let i=rowid; i<tailRow; i++) {  //高级模式可多行
                        trDataArr.push(<LayoutTr
                            key={`${i}_${rowIndex}`}
                            symbol={symbol}
                            colNum={colHeads.length}
                            rowid={i}
                            rowHeight={`${rowheads[`row_${i}`]||30}px`}
                            rowCusAttr={rowCusAttr}
                            colattrs={colattrs}
                            ecMap={ecMap}
                            detailProps={detailProps}
                            dataRows={dataRows}
                            rowMergeInfo={currentPageRowMergeInfo && currentPageRowMergeInfo.get(`row_${rowIndex}`)}
                        />);
                    }
                });
            }else if(rowid < headRow || (isSeniorSet && rowid > tailRow)){  //头尾非数据行
                if(!isSeniorSet)
                    addColType = (rowid === headRow-1) ? 2 : 1;
                const detailTr = (
                    <LayoutTr
                        key={`row_${rowid}`}
                        symbol={symbol}
                        colNum={colHeads.length}
                        rowid={rowid}
                        rowHeight={`${rowheads[`row_${rowid}`]||30}px`}
                        rowCusAttr={rowCusAttr}
                        colattrs={colattrs}
                        ecMap={ecMap}
                        detailProps={{addColType}}
                    />
                );
                if(rowid < headRow)
                    trHeadArr.push(detailTr);
                else
                    trTailArr.push(detailTr);
            }
        });
        if(!isSeniorSet && DetailUtil.judgeDetailContainSum(symbol)){     //扩充添加合计行
            trTailArr.push(<LayoutTr
                key="virtualSumRow"
                symbol={symbol}
                colNum={colHeads.length}
                rowid={headRow-1}   //合计行样式取字段标签所在行
                rowHeight="30px"
                colattrs={colattrs}
                ecMap={ecMap}
                detailProps={{addColType:4}}
            />);
        }
        return (
            <div className="wf-detail">
            <div className="excelDetailTableDiv" id={`dTableArea_${groupid}`} data-groupid={groupid} data-allowxscroll={allowXScroll}>
                <div className="excelDetailFixedHead">
                    <table className="excelDetailTable" id={`oTable${groupid}_head`} style={tableStyle}>
                        <tbody>
                            {trHeadArr}
                        </tbody>
                    </table>
                </div>
                {/* <div className={"excelDetailContent"} style={divStyle} onScroll={this.doScrollXEvent.bind(this)}> */}
                <div className={divClassName} onScroll={this.doScrollXEvent.bind(this)}>
                    <table className="excelDetailTable" id={`oTable${groupid}`} name={`oTable${groupid}`} style={tableStyle}>
                        <tbody>
                            {trHeadArr}
                            {trDataArr}
                            {this.generatePaginationTr(colTdArr.length)}
                            {trTailArr}
                        </tbody>
                    </table>
                </div>
            </div>
            </div>
        )
    }
    generatePaginationTr(colspan){
        const { symbol,wfGlobalStore,wfLayoutStore } = this.props;
        const { workflowid } = wfGlobalStore.commonParam;
        const { dataJson,detailMap } = wfLayoutStore;
        const detailLayout = dataJson.etables[symbol] || {};
        const headRow = parseInt(detailLayout.edtitleinrow || 0);
        const detailObj = detailMap.get(symbol);
        const groupid = detailObj.attr.groupid - 1;
        const { pagingInfo,rowInfoArr } = detailObj;
        const total = rowInfoArr.length;
        let { enabled,current,pagesize } = pagingInfo;
        if(!enabled)
            return null;
        const pagesizeArr = [10, 20, 30, 50, 100, 150, 200];
        const options = [];
        pagesizeArr.map(size =>{
            options.push({value:size, label:`${size}条/页`});
        });
        const totalPage = Math.ceil(total/pagesize);
        if(totalPage === 0)
            current = 0;
        const firstBtn = current > 1;
        const preBtn = current > 1;
        const nextBtn = current < totalPage;
        const lastBtn = current < totalPage;
        return (
            <tr>
                <td colSpan={colspan} className={`${symbol}_${headRow+1}_0`} style={{height:"30px"}}>
                    <div className="wf-detail-paging">
                        <div className="wf-detail-pagesize">
                            <Picker 
                                data={options} 
                                cols={1} 
                                onChange={data =>{
                                    const params = { workflowid, groupid, pagesize:data[0]};
                                    detailObj.changePageSize(params);
                                    DetailUtil.controlDetailPosition(groupid);
                                }}
                                value={[pagesize]}
                            >
                                <div className="wf-detail-pagesize-switch">{`${pagesize}${getLabel(386261,"条/页")}`}</div>
                            </Picker>
                        </div>
                        <div className="wf-detail-pageinfo">
                            {`${current}/${totalPage}`}
                        </div>
                        <div className="wf-detail-switch-btn">
                            <Icon type="home-page-1" onClick={()=>{
                                firstBtn && this.doSwitchPage(1);
                            }} />
                        </div>
                        <div className="wf-detail-switch-btn">
                            <Icon type="arrow-left" onClick={()=>{
                                preBtn && this.doSwitchPage(current-1);
                            }} />
                        </div>
                        <div className="wf-detail-switch-btn">
                            <Icon type="arrow-right" onClick={()=>{
                                nextBtn && this.doSwitchPage(current+1);
                            }} />
                        </div>
                        <div className="wf-detail-switch-btn">
                            <Icon type="tail-page" onClick={()=>{
                                lastBtn && this.doSwitchPage(totalPage);
                            }} />
                        </div>
                    </div>
                </td>
            </tr>
        )
    }
    doSwitchPage(current){
        const { symbol,wfLayoutStore } = this.props;
        const { detailMap } = wfLayoutStore;
        const detailObj = detailMap.get(symbol);
        const groupid = detailObj.attr.groupid - 1;
        detailObj.controlPagingInfo({current});
        DetailUtil.controlDetailPosition(groupid);
    }
    doScrollXEvent(){
        const { symbol } = this.props;
        const groupid = parseInt(symbol.substring(7)) - 1;
        DetailUtil.syncDetailScrollXPosition(groupid);
    }
}
